package com.concurrency.aqs;

import java.util.concurrent.TimeUnit;

/**
 * <p>线程中断机制：在java中如何优雅的中断线程</p>
 * <li>interrupt(): 只是为了设置中断标志</li>
 * <li>interrupted(): 测试当前线程是否中断，会清除中断标识</li>
 * <li>isInterrupted: 测试当前线程是否中断，不会清除中断标识</li>
 * <li>用线程的中断机制比volatile标志变量的方式的优势是，用中断机制可以中断阻塞的线程</li>
 *
 */
public class ThreadInterruptTest {
    static int i = 0;
    static Object object = new Object();

    public static void main(String[] args) {
        System.out.println("start");
        Thread t1 = new Thread(() -> {
            while (true) {
                i++;
                System.out.println(i);

                synchronized (object) {
                    try {
                        object.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                if (Thread.interrupted()) {
                    System.out.println("==========");
                }
//                if (Thread.currentThread().isInterrupted()) {
//                    System.out.println("==========");
//                }
                if (i == 10) break;
            }
        }, "thread-1");
        t1.start();
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t1.interrupt();
    }

}
